/*************************************************************
 * Title: DateHelper.java
 * Description: 
 * Author: Huang Shaobin
 * Email: shaobin.software@gmail.com
 * CreateTime: Feb 22, 2013 6:01:13 PM
 * Description:
 ************************************************************/
package snow.core.toolkit;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 */
public class DateHelper {

	private static final Map<String, DateFormat> DATE_FORMAT_MAP = new ConcurrentHashMap<String, DateFormat>();

	private static final Object mutex = new Object(); // 线程锁

	static {
		DATE_FORMAT_MAP.put("yyyy-MM-dd HH:mm:ss.SSS", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"));
		DATE_FORMAT_MAP.put("yyyy-MM-dd HH:mm:ss", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
		DATE_FORMAT_MAP.put("yyyy-MM-dd", new SimpleDateFormat("yyyy-MM-dd"));
	}

	public static String format(final Date date, final String format) {
		return getDateFormatFrom(format).format(date);
	}

	public static DateFormat getDateFormatFrom(final String format) {
		DateFormat dateFormat = DATE_FORMAT_MAP.get(format);
		if (dateFormat == null) {
			synchronized (mutex) {
				dateFormat = DATE_FORMAT_MAP.get(format);
				if (dateFormat == null) {
					dateFormat = new SimpleDateFormat(format);
					DATE_FORMAT_MAP.put(format, dateFormat);
				}
			}
		}
		return dateFormat;
	}

	public static Date parse(String source, String format) {
		try {
			Date date = getDateFormatFrom(format).parse(source);
			if (date == null) {
				Set<String> keySet = DATE_FORMAT_MAP.keySet();
				for (String key : keySet) {
					date = DATE_FORMAT_MAP.get(key).parse(source);
					if (date != null) {
						break;
					}
				}
			}
			return date;
		} catch (Exception e) {
			return null;
		}
	}

}
